﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using Citi.FinancePlanningAnalysis.Domain;
using Citi.Helpers;
using Citi.RoutineBase;
using Citi.SecurityHelper;

namespace Citi.FinancePlanningAnalysis.SchedulerUi
{
    public class AccountImport : GeneralImport
    {
        public override string ExcelPath { get { return ConfigurationManager.AppSettings["AccountExcelPath"]; } }
        public override List<string> Files { get; set; }
        public override string QueryMergeDate { get { return Account.QueryMergeDate; } }
        public override string QueryDeletePrevious { get { return Account.QueryDeletePrevious; } }
        public override string QueryExcel { get { return Account.QueryExcel; } }
        public override string TableTemp { get { return "AccountTemp"; } }
        public override Dictionary<string, string> ExcelColumnMappings { get { return Account.ExcelColumnMappings; } }
        public override string SheetName { get { return "Table Format"; } }

        public override void PrepareFiles(DateTime scheduledDate, ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            DownloadFeed(currentAction, scheduledDate, parameters["SoeidResponsible"].ToString());

            Files = Directory.GetFiles(Path.Combine(ExcelPath, "Zips")).Where(x => x.EndsWith(".xls") || x.EndsWith(".xlsx")).ToList();
        }

        private string DownloadFeed(ICurrentAction currentAction, DateTime referenceDate, string soeidResponsible)
        {
            var fileName = string.Format(ConfigurationManager.AppSettings["CoaFileName"], DateTime.Today.ToString("MMMyyyy", new CultureInfo("EN-US")));
            string filePath;
            var fileDownloaded = Path.Combine(ExcelPath, string.Format("{0}_{1}{2}", Path.GetFileNameWithoutExtension(fileName)
                , DateTime.Today.ToString("yyyyMMdd"), Path.GetExtension(fileName)));

            currentAction.Description = string.Format("Downloading feed to {0}", fileDownloaded);

            fileName = DownloadFile(soeidResponsible, fileName, fileDownloaded, currentAction);

            var directoryToSave = Path.Combine(ExcelPath, "Zips");
            if (!Directory.Exists(directoryToSave)) Directory.CreateDirectory(directoryToSave);

            currentAction.Description = "Decompressing files";
            FileHelper.Decompress(fileDownloaded, directoryToSave);
            File.Delete(fileDownloaded);

            filePath = Directory.GetFiles(directoryToSave).FirstOrDefault(x => Path.GetExtension(x) == ".xls" || Path.GetExtension(x) == ".xlsx");

            var newFileName = Path.Combine(Path.GetDirectoryName(filePath),
                string.Format("{0}_{1}{2}", Path.GetFileNameWithoutExtension(filePath), referenceDate.ToString("yyyyMM"), Path.GetExtension(filePath)));

            File.Copy(filePath, newFileName, true);
            File.Delete(filePath);
            filePath = newFileName.Replace(Path.GetExtension(filePath), string.Empty);

            return filePath;
        }

        private static string DownloadFile(string soeidResponsible, string fileName, string fileDownloaded, ICurrentAction currentAction)
        {
            try
            {
                currentAction.Description = string.Format("Trying to download: '{0}'", fileName);
                SecurityDownload.DownloadRemoteFile(fileName, fileDownloaded, soeidResponsible, ConfigurationManager.AppSettings["Proxy"]);
            }
            catch
            {
                //If current month was not found. Try to find previous month
                fileName = string.Format(ConfigurationManager.AppSettings["CoaFileName"], DateTime.Today.AddMonths(-1).ToString("MMMyyyy", new CultureInfo("EN-US")));
                try
                {
                    currentAction.Description = string.Format("Trying to download: '{0}'", fileName);
                    SecurityDownload.DownloadRemoteFile(fileName, fileDownloaded, soeidResponsible, ConfigurationManager.AppSettings["Proxy"]);
                }
                catch
                {
                    //If current month was not found. Try to find using format 'MMMyy'
                    fileName = string.Format(ConfigurationManager.AppSettings["CoaFileName"], DateTime.Today.ToString("MMMyy", new CultureInfo("EN-US")));
                    try
                    {
                        currentAction.Description = string.Format("Trying to download: '{0}'", fileName);
                        SecurityDownload.DownloadRemoteFile(fileName, fileDownloaded, soeidResponsible, ConfigurationManager.AppSettings["Proxy"]);
                    }
                    catch
                    {
                        //If current month was not found. Try to find previous month using format 'MMMyy'
                        fileName = string.Format(ConfigurationManager.AppSettings["CoaFileName"], DateTime.Today.AddMonths(-1).ToString("MMMyy", new CultureInfo("EN-US")));
                        try
                        {
                            currentAction.Description = string.Format("Trying to download: '{0}'", fileName);
                            SecurityDownload.DownloadRemoteFile(fileName, fileDownloaded, soeidResponsible, ConfigurationManager.AppSettings["Proxy"]);
                        }
                        catch
                        {
                            throw;
                        }
                    }
                }
            }

            return fileName;
        }

        public override void FinishImport(ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            throw new NotImplementedException();
        }
    }
}
